var express = require('express');
let tencentcloud = require('tencentcloud-sdk-nodejs-iai');
var app = express.Router()
var jwt = require('jsonwebtoken')
var svgCaptcha = require('svg-captcha');
const { Fu_user, loginModel } = require('../mondules/fu/fu_module')
const { historicalModel } = require('../mondules/jwh/jwh')
const {wsyList,wsyshop } = require('../mondules/fu/fu_module')


require('dotenv').config();
const axios = require('axios');
const DEEPSEEK_URl = 'https://api.deepseek.com/v1/chat/completions'
const DEEPSEEK_MODEL = 'deepseek-chat';


// 处理聊天请求
app.post('/api/chat', async (req, res) => {
  const { messages } = req.body;
  const maxRetries = 10;
  let attempt = 0;
  let success = false;
  let response;

  while (attempt < maxRetries && !success) {
    try {
      response = await axios.post(DEEPSEEK_URl, {
        model: DEEPSEEK_MODEL,
        messages,
        temperature: 0.7,
      }, {
        headers: {
          'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`,
          'Content-Type': 'application/json'
        }
      });
      success = true;
    } catch (error) {
      attempt++;
      console.log(`Attempt ${attempt} failed:`, error.response?.data || error.message);
      if (attempt >= maxRetries) {
        res.status(error.response?.status || 500).json({
          error: error.response?.data?.error?.message || 'internal server error'
        });
        return;
      }
    }
  }

  console.log(response.data);
  res.json(response.data);
});

// 历史记录保存

app.post('/jwh/historical', async (req, res) => {
  let body = req.body
  console.log('body:', body)
  const time = new Date().getTime()
  if (!body._id) {
    const result = await historicalModel.create({ userId: body.userId, content: JSON.stringify(body.content), time: time })
    res.send({
      code: 200,
      msg: '添加成功',
      id: result._id
    })
  } else {
    const result = await historicalModel.updateOne({ _id: body._id }, { content: JSON.stringify(body.content), time: time })
    console.log('result:', result)
    res.send({
      code: 200,
      msg: '修改成功',
      id: body._id
    })
  }
})

app.post('/jwh/getHistorical', async (req, res) => {
  const _id = req.body.id
  console.log('id:', _id)
  let dates = await historicalModel.find({ userId: _id })
  res.send({
    code: 200,
    msg: '显示成功',
    dates
  })
})









// --------------------------------------------后端登录逻辑--------------------------------------------------------------






//登录页负责人 ！~杨帆
app.post('/loginS', async (req, res) => {
  let { data: { phone, seconds, password } } = req.body;
  

  let arr = [{}];
  if (phone) {
    arr.push({
      phone: phone,
    });
  }
  if (password){
    arr.push({
      password: password,
    });
  }
  if (seconds) {
    arr.push({
      seconds: seconds,
    });
  }
  let user = await loginModel.find({ $and: arr });
  if (user.length > 0) {
    let token = "Bearer " + jwt.sign({ username: user.username }, '123', { expiresIn: '3h' });
    res.send({
      code: 200,
      msg: '登录成功',
      token
    });
  } else {
    res.send({
      code: 201,
      msg: '登录失败，账号或密码出现错误'
    });
  }

})
//添加登录信息
app.post('/addLogin', async (req, res) => {
  let addfrom = req.body
  loginModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

//用户提供图片验证码
app.post('/svgCode', async (req, res) => {
  let info = svgCaptcha.create({
    size: 4,//验证码长度
    ignoreChars: '0o1i',//验证码字符中排除 0o1i 默认是以a-z A-z 0-9去生成的随机验证码
    noise: 1,//干扰线条的数量
    color: true,//验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
    background: 'RGB(100,150,234)',//验证码图片背景颜色
    width: 70, // 宽度 
    height: 30, // 高度
    fontSize: 30,
    characterSet: '1234567890',
    fontSize: '50',
    color:'white'
    // data图形验证码
    // text字符串形式的验证码

  })
  let userlist = await loginModel.find()

  res.send({
    code: 200,
    msg: '显示成功',
    info,
    userlist
  })
});
//修改用户验证码
app.post('/updateId', async (req, res) => {
  let body = req.body
  let _id = body
  await loginModel.updateOne({ _id }, body)
  res.send({
    code: 200,
    msg: '修改成功',
  })
});
// 登录个人信息
app.post('/loginREN', async (req, res) => {
  let listLogin =await loginModel.find()
  let token = "bearer " + jwt.sign({ username: listLogin.phone }, '123', { expiresIn: '3h' });
  res.send({
    code: 200,
    msg: '显示成功',
    listLogin,
    token
  })
});

//人脸登录
app.post('/faceLogin', async function (req, res) {
  const base64 = req.body.base64; //base64是前端传递过来要进行对比的照片的base64格式
  const IaiClient = tencentcloud.iai.v20200303.Client;
  const clientConfig = {
    credential: {
      secretId: 'AKIDazDNXVGtIdolT7b1mY8WmdGfrpZ7RXR9',
      secretKey: 'Y1HJ9l9KG0aw86pVEMHyTr34tZ4XFpKn',
    },
    region: 'ap-beijing',
    profile: {
      httpProfile: {
        endpoint: 'iai.tencentcloudapi.com',
      },
    },
  };
  // 实例化要请求产品的client对象,clientProfile是可选的
  const client = new IaiClient(clientConfig);
  //请求参数
  const params = {
    GroupIds: [
      //人员库ID 自己创建的人员库ID 替换成自己的
      '00001',
      '0002',
      '00003',
    ],
    Image: base64, //前端传来的图片base64编码
    NeedPersonInfo: 1, //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    QualityControl: 0, //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    FaceMatchThreshold: 85, //人脸对比度大于85才匹配通过
  };
  //发送请求
  const { Results } = await client.SearchFaces(params);

  //判断如果没有匹配到
  if (Results[0].Candidates.length === 0) {
    res.json({
      code: -1,
      msg: '该人员没有注册',
    });
    return;
  }
  //匹配到则返回用户信息
  const { FaceId, Gender, PersonId, PersonName } = Results[0].Candidates[0];
  res.send({
    code: 200,
    data: {
      FaceId,
      Gender,
      PersonId,
      PersonName,
    },
    msg: '识别成功',
  });
});

//修改个人信息
app.post('/nameUpdatef', async (req, res) => {
  let body = req.body
  let phone = body.phone

  await loginModel.updateOne({ phone }, body)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})




app.get('/wlist', async(req, res) => {
  const {name,address}=req.query
    const reg=[{}]
    const regname=new RegExp(name)
    const regaddress=new RegExp(address)
  if(name){
   reg.push({name:{$regex:regname}})
  }
  if(address){
    reg.push({address:regaddress})
  }
  const data = await wsyList.find({$and:reg})
  res.send({
    code: 200,
    data
  })
})

app.get('/wshop',async(req,res)=>{
  const data=await wsyshop.find()
  res.send({
    code:200,
    data
  })
})




module.exports = app;